package com.jd.dlc.lock;

import com.jd.gms.lock.utils.JimDbLockUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @program: dlc
 * @ClassName DistributedLockManager
 * @description:
 * @author: sizegang
 * @create: 2022-05-02
 **/
public class DistributedLockManager implements Lock {

    Logger log = LoggerFactory.getLogger(DistributedLockManager.class);

    @Autowired
    @Qualifier("jimDbLockUtils")
    private JimDbLockUtils jimDbLockUtils;


    /**
     * @param lockKey   锁的key
     * @param lockValue 请求的唯一标识。对于不同的请求，需要不同的值。防止在释放时，释放了别的请求持有的锁。可以使用requestId
     * @param expire    失效时间 需要大与0
     * @param timeUnit  失效时间单位
     * @return boolean
     * @Descrption 尝试获取分布式锁的功能
     * @date 2022/2/28
     */
    public boolean tryRequiredLock(String lockKey, String lockValue, int expire, TimeUnit timeUnit) {
        if (StringUtils.isEmpty(lockKey) || StringUtils.isEmpty(lockValue)
                || expire <= 0 || Objects.isNull(timeUnit)) {
            log.info("参数问题，不获取锁 key:{}", lockKey);
            return false;
        }
        boolean result = jimDbLockUtils.tryGetDistributedLock(lockKey, lockValue, timeUnit, expire);
//        log.info("获取分布式锁参数：key:{} value:{} expire:{}, timeUnit:{} result:{}", lockKey, lockValue,
//                expire, timeUnit, result);
        return result;
    }

    /**
     * @param lockKey   锁的key
     * @param lockValue 锁key对应的请求id
     * @return boolean
     * @Descrption 释放锁
     * @date 2022/2/28
     */
    public boolean releaseLock(String lockKey, String lockValue) {
        if (StringUtils.isEmpty(lockKey) || StringUtils.isEmpty(lockValue)) {
            log.info("参数问题，无法释放锁 key:{} value:{}", lockKey, lockValue);
            return false;
        }
        boolean result = jimDbLockUtils.releaseDistributedLock(lockKey, lockValue);
//        log.info("释放分布式锁参数：key:{} value:{} result:{}", lockKey, lockValue, result);
        return result;
    }
}